<template>
  <view class="container">
    <view class="section">
      <button @click="downloadNetworkImage" class="custom-btn download-btn">下载网络图片</button>
      <image v-if="networkImageUrl" :src="networkImageUrl" mode="widthFix" class="preview-image"></image>
      <view v-if="downloadProgress > 0 && downloadProgress < 100" class="progress-tip">
        下载进度：{{ downloadProgress }}%
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      networkImageUrl: '',
      downloadProgress: 0
    }
  },
  methods: {
    downloadNetworkImage() {
      this.downloadProgress = 0;
      const downloadTask = uni.downloadFile({
        url: 'https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg',
        success: (res) => {
          if (res.statusCode === 200) {
            this.downloadProgress = 100;
            this.networkImageUrl = res.tempFilePath;
            uni.showToast({
              title: '图片下载完成',
              icon: 'success'
            });
            setTimeout(() => {
              this.downloadProgress = 0;
            }, 3000);
          }
        },
        fail: (err) => {
          console.error('下载图片失败：', err);
          this.downloadProgress = 0;
          uni.showToast({
            title: '图片下载失败',
            icon: 'none'
          });
        }
      });

      downloadTask.onProgressUpdate((res) => {
        this.downloadProgress = res.progress;
        // 明确打印日志，包含已下载和总字节数
        console.log(`下载进度：${res.progress}%，已下载：${res.totalBytesWritten}字节，总大小：${res.totalBytesExpectedToWrite}字节`);
      });
    }
  }
}
</script>

<style scoped>
.download-btn {
  background-color: #3CD6FF;
}

.section {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.preview-image {
  width: 500rpx;
  height: 300rpx;
  border-radius: 16rpx;
  overflow: hidden;
  border: 1rpx solid #eee;
}

.progress-tip {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  margin-top: 10rpx;
}
</style>